function Get-StatSPOnlineWebSession
{
    <# 
        .SYNOPSIS
            Retrieves SharePoint Online tenant account details from the associated account configuration file and establishes a connection to the tenant

        .DESCRIPTION
            Part of the SharePoint Total Automation Toolkit (STAT). This function reads in a single data row from SharePoint Online Account file when called. It then establishes a connection to the SharePoint Online tenant.
            
            If the configuration files are stored in the standard path and structure, you have the option of specifying each discrete parameter. Alternatively you can provide the full path to the configuration directory.
 
        .EXAMPLE
            Get-StatSPOnlineWebSession -Company Contoso -Project SharePointOnline -Release 1.0.0.0 -Environment Development

            If using the default configuration file path and structure, you can provide discrete parameters to each subdirectory.

        .EXAMPLE
            Get-StatSPOnlineWebSession -ConfigPath 'C:\ProgramData\SharePoint Total Automation Toolkit\Configuration Files\Contoso\SharePointOnline\1.0.0.0\Development'

            Using the -ConfiPath parameter allows you to directly specify the full path to the configuration files that control the process.

        .EXAMPLE
            $myFullPath | Get-StatSPOnlineWebSession

            This function accepts pipeline input for the -ConfiPath parameter which allows you to directly specify the full path to the configuration files that control the process.

        .PARAMETER StatAccountLookup
            The internal STAT name that this function will use when querying the tenant account list for account details such as the username and password. If no account is provided, the SharePoint Administrator account will be used.

        .PARAMETER Company
            The company subdirectory (e.g. Contoso)
            Part of the overall path to the configuration files that control the installation process

        .PARAMETER Project
            The project subdirectory (e.g. SharePointOnline)
            Part of the overall path to the configuration files that control the installation process

        .PARAMETER Release
            The release subdirectory (e.g. 1.0.0.0)
            Part of the overall path to the configuration files that control the installation process

        .PARAMETER Environment
            The target environment subdirectory (e.g. Development)
            Part of the overall path to the configuration files that control the installation process

        .PARAMETER ConfigPath
            The full path to the configuration files that control the installation process
            (e.g. 'C:\ProgramData\SharePoint Total Automation Toolkit\Configuration Files\Contoso\SharePointOnline\1.0.0.0\Development')

        .INPUTS
            TenantInfo-SPOnlineDetails.csv
            TenantInfo-Accounts.csv

            Although not technically PowerShell "inputs", this function requires one or more comma separated value (CSV) files to be present at the configuration file path specified in the parameters or at the file path provided on the pipeline input.
            
            -------------------------- FILE 1 --------------------------

            TenantInfo-SPOnlineDetails.csv

            The associated configuration file must have a header row with the following field names:
                SiteUrl
        
            The following are valid values for the associated fields:

                SiteUrl
                    The URL of the SharePoint Online site

                    Required?     true
                    Example       https://yourtenant.sharepoint.com


            -------------------------- FILE 2 --------------------------

            TenantInfo-Accounts.csv

            The associated configuration file must have a header row with the following field names:
                StatAccountLookup,UserName,Password
        
            The following are valid values for the associated fields:

                StatAccountLookup
                    The internal name used by SharePoint Total Automation Toolkit (STAT)
                    to query this file for account details such as the username and password

                    Required?     true
                    Example       SharePoint Search Crawler

                UserName
                    The SharePoint Online logon name for the account

                    Required?     true
                    Example       admin@yourtenant.onmicrosoft.com

                Password
                    The password for the account

                    Required?     true
                    Example       pass@word1

    #>
    [CmdletBinding(DefaultParametersetName="DiscreteValues")]
    param([parameter(ParameterSetName = "DiscreteValues", 
                     Mandatory = $true,
                     HelpMessage = "The company subdirectory (e.g. Contoso). Part of the overall path to the configuration files that control the installation process")]
                     [string]$Company,
          [parameter(ParameterSetName = "DiscreteValues", 
                     Mandatory = $true,
                     HelpMessage = "The project subdirectory (e.g. Intranet). Part of the overall path to the configuration files that control the installation process")]
                     [string]$Project,
          [parameter(ParameterSetName = "DiscreteValues", 
                     Mandatory = $true,
                     HelpMessage = "The release subdirectory (e.g. 1.0.0.0). Part of the overall path to the configuration files that control the installation process")]
                     [string]$Release,
          [parameter(ParameterSetName = "DiscreteValues", 
                     Mandatory = $true,
                     HelpMessage = "The target environment subdirectory (e.g. Development). Part of the overall path to the configuration files that control the installation process")]
                     [string]$Environment,
          [parameter(ParameterSetName = "FullPath", 
                     Mandatory = $true,
                     ValueFromPipeline=$true,
                     ValueFromPipelineByPropertyName=$true, 
                     HelpMessage = "The full path to the configuration files that control the installation process. (e.g. 'C:\ProgramData\SharePoint Total Automation Toolkit\Configuration Files\Contoso\Intranet\1.0.0.0\Development'")]
                     [string]$ConfigPath,
          [parameter(ParameterSetName = "DiscreteValues", 
                     Mandatory = $false,
                     HelpMessage = "The internal STAT name that this function will use when querying the tenant account list for account details such as the username and password")]
          [parameter(ParameterSetName = "FullPath", 
                     Mandatory = $false,
                     HelpMessage = "The internal STAT name that this function will use when querying the tenant account list for account details such as the username and password")]
                     [string]$StatAccountLookup="SharePoint Administrator")

    switch ($PSCmdlet.ParameterSetName)
    {
        "DiscreteValues"
        {
            $ConfigPath = $env:ProgramData + "\SharePoint Total Automation Toolkit\Configuration Files\" + $Company + "\" + $Project + "\" + $Release + "\" + $Environment
        }    
        "FullPath"
        {
        }
    }

    # Version Compatibility Check Variable
    $firstCompatibleVersion = "0.1.0.0"

    # Conduct Version Compatibility Check
    if ((ConfigVersionIsCompatible $firstCompatibleVersion $ConfigPath))
    {
        $tenantSiteInfo = Get-StatSPOnlineTenantInfo -ConfigPath $ConfigPath 
        $tenantSiteUrl = $tenantSiteInfo.BaseUri

        $connectionAccount = Get-StatSPOnlineAccount -ConfigPath $ConfigPath -StatAccountLookup $StatAccountLookup

        [System.Xml.XmlDocument]$requestSecurityToken = 
        @"
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
      xmlns:a="http://www.w3.org/2005/08/addressing"
      xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
  <s:Header>
    <a:Action s:mustUnderstand="1">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</a:Action>
    <a:ReplyTo>
      <a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
    </a:ReplyTo>
    <a:To s:mustUnderstand="1">https://login.microsoftonline.com/extSTS.srf</a:To>
    <o:Security s:mustUnderstand="1"
       xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
      <o:UsernameToken>
        <o:Username></o:Username>
        <o:Password></o:Password>
      </o:UsernameToken>
    </o:Security>
  </s:Header>
  <s:Body>
    <t:RequestSecurityToken xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">
      <wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
        <a:EndpointReference>
          <a:Address></a:Address>
        </a:EndpointReference>
      </wsp:AppliesTo>
      <t:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</t:KeyType>
      <t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType>
      <t:TokenType>urn:oasis:names:tc:SAML:1.0:assertion</t:TokenType>
    </t:RequestSecurityToken>
  </s:Body>
</s:Envelope>
"@

        $requestSecurityToken.Envelope.Header.Security.UserNameToken.UserName = $connectionAccount.UserName
        $requestSecurityToken.Envelope.Header.Security.UserNameToken.Password = $connectionAccount.Password
        $requestSecurityToken.Envelope.Body.RequestSecurityToken.AppliesTo.EndpointReference.Address = $tenantSiteUrl

        $authenticationURL = "https://login.microsoftonline.com/extSTS.srf"

        $securityToken = Invoke-WebRequest -Uri $authenticationURL -Method Post -ContentType "text/xml" -Body $requestSecurityToken -UserAgent ([Microsoft.PowerShell.Commands.PSUserAgent]::InternetExplorer)
        $binaryToken = ([xml]$securityToken.Content).Envelope.Body.RequestSecurityTokenResponse.RequestedSecurityToken.BinarySecurityToken."#text"

        $siteTokenConverter = $tenantSiteUrl + "/_forms/default.aspx?wa=wsignin1.0"

        $authenticationCookieResponse = Invoke-WebRequest -Uri $siteTokenConverter -Method Post -ContentType "text/xml" -Body $binaryToken -UserAgent ([Microsoft.PowerShell.Commands.PSUserAgent]::InternetExplorer) -SessionVariable session


        $contextUri = $tenantSiteUrl + "/_api/contextinfo"
        $contextHeaders =  @{"accept"="application/json; odata=verbose"}
        $contextJSON = Invoke-WebRequest -Headers $contextHeaders -WebSession $session -Uri $contextUri -Method POST
        $context = $contextJSON.Content | ConvertFrom-Json

        # Create our return object
        $tenantData = New-Object PSObject -Property @{BaseUri = $tenantSiteUrl;
                                                      Session = $session;
                                                      FormDigestValue = $context.d.GetContextWebInformation.FormDigestValue}

        return $tenantData
    }
    else
    {
        Write-Host "     ERROR:" -ForegroundColor Red
        Write-Host "     This script requires configuration files at version" $firstCompatibleVersion "or higher." -ForegroundColor Red
        Write-Host "     Use the Get-Help command for a complete list of the configuration files used by this script." -ForegroundColor Red

    }
}